package so.sao.shop.supplier.web;

import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import so.sao.shop.supplier.config.Constant;
import so.sao.shop.supplier.domain.Account;
import so.sao.shop.supplier.domain.DictItem;
import so.sao.shop.supplier.domain.SysRegion;
import so.sao.shop.supplier.domain.User;
import so.sao.shop.supplier.pojo.Result;
import so.sao.shop.supplier.pojo.input.AccountInput;
import so.sao.shop.supplier.pojo.vo.UserVo;
import so.sao.shop.supplier.service.AccountService;
import so.sao.shop.supplier.service.AuthService;
import so.sao.shop.supplier.service.SysRegionService;
import so.sao.shop.supplier.service.UserService;
import so.sao.shop.supplier.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xujc on 2017/7/18.
 */
@RestController
@RequestMapping("/account")
public class AccountController {
	/**
	 * 初始化日志
	 */
	private final Logger logger = LoggerFactory.getLogger(this.getClass());


    @Autowired
    private AccountService accountService;

    @Autowired
    private AuthService authService;

    @Autowired
    private SysRegionService sysRegionService;

    @Autowired
    private UserService userService;

    /**
     * 单次添加供应商信息
     *
     * @param account 供应商信息
     * @return 返回添加结果
     */
    @PostMapping("/save")
    public Result save(@Valid @RequestBody Account account) throws Exception{
        //获取当前登陆账户
        User user = JwtTokenUtil.getCurrentUser();
        if(user==null || !user.getIsAdmin().equals(Constant.ADMIN_STATUS)){
            return Result.fail(Constant.MessageConfig.ADMIN_AUTHORITY_EERO);
        }
        /**
         * 插入用户和供应商信息
         */
		return accountService.saveUserAndAccount(account);
    }

    /**
     * 更新供应商信息
     *
     * @param account 供应商对象
     * @return 返回更新成功或者失败
     */
    @PutMapping("/update")
    public Result update(@Valid @RequestBody Account account) throws Exception{
        //获取当前登陆账户
        User user = JwtTokenUtil.getCurrentUser();
        if(user==null || !user.getIsAdmin().equals(Constant.ADMIN_STATUS)){
            return Result.fail(Constant.MessageConfig.ADMIN_AUTHORITY_EERO);
        }
        return accountService.updateAccountAndUser(account);
    }

    /**
     * 根据id删除供应商信息
     *
     * @param id
     * @return 返回成功或失败
     */
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Long id) throws Exception{
        //获取当前登陆账户
        User user = JwtTokenUtil.getCurrentUser();
        if(user==null || !user.getIsAdmin().equals(Constant.ADMIN_STATUS)){
            return Result.fail(Constant.MessageConfig.ADMIN_AUTHORITY_EERO);
        }
        return accountService.delete(id);
    }

    /**
     * 初始化银行信息
     *
     * @return
     */
    @GetMapping("/selectBank")
    public List<String> selectBank() {
        return accountService.selectBank();
    }

    /**
     * 初始化行业信息
     *
     * @return
     */
    @GetMapping("/selectHangYe")
    public List<String> selectHangYe() {
        return accountService.selectHangYe();
    }

    /**
     * 初始化行业信息
     *
     * @return
     */
    @GetMapping("/selectHangYeDict")
    public List<DictItem> selectHangYeDict() {
        return accountService.selectHangYeDict();
    }

    /**
     * 登陆获取token
     *
     * @param authenticationRequest
     * @return
     * @throws AuthenticationException
     * @throws IOException
     */
    @PostMapping(value = "${jwt.route.authentication.path}")
    public Result<String> createAuthenticationToken(
              @RequestBody User authenticationRequest, HttpServletRequest request) throws AuthenticationException, IOException {
        Result<String> result = authService.login(authenticationRequest.getUsername(), authenticationRequest.getPassword());
        if(Constant.CodeConfig.CODE_SUCCESS.equals(result.getCode())){
            logger.info("用户:{},ip:{}登陆成功",authenticationRequest.getUsername(),IPUtil.getIpAddress(request));
        }else{
            logger.info("用户:{},ip:{}尝试登陆",authenticationRequest.getUsername(),IPUtil.getIpAddress(request));
        }
        return result;
    }

    /**
     * 获取admin标记(一期暂时)
     *
     * @return
     */
    @GetMapping(value = "/isAdmin")
    public Result isAdmin(){
        Map result = new HashMap();
        //获取当前登陆账户
        User user = JwtTokenUtil.getCurrentUser();
        result.put("isAdmin",user.getIsAdmin());
        return Result.success("", result);
    }

    /**
     * 获取当前登陆供应商名
     * @return
     */
    @GetMapping(value = "/username")
    public Result<?> getUserName(){
        Map<String,Object> result = new HashMap<String,Object>();
        User user = JwtTokenUtil.getCurrentUser();
        UserVo userVo = userService.findById(user.getId());
        if ( "0".equals(userVo.getIsAdmin())) {
            //供应商
            Account account = accountService.selectByUserId(userVo.getParentId() != 1 ? userVo.getParentId() : userVo.getId());
            result.put("username",account.getProviderName());
        } else if ( "1".equals(userVo.getIsAdmin())) {
            //管理员及其子账号
            Account account = accountService.selectByUserId(userVo.getId());
            result.put("username",account == null ? userVo.getUsername() : account.getProviderName());
        } else if ("2".equals(userVo.getIsAdmin())) {
            //财务账号
            Account account = accountService.selectByUserId(userVo.getId());
            result.put("username", account.getProviderName());
        }

        /*Account account = accountService.selectById0(user.getAccountId());
        if (account == null) {
            user = userService.findById(user.getId());
        }
        result.put("username",account!=null?account.getProviderName():user.getUsername());*/
        return Result.success("", result);
    }

    /**
     * 登出,设置登出时间
     *
     * @return
     */
    @PostMapping(value = "/logout")
    public Result<String> logout() {
        //获取当前登陆账户
        User user = JwtTokenUtil.getCurrentUser();
        return authService.logout(user);
    }

    /**
     * 根据用户ID查询用户的实时余额
     * @param request
     * @return
     */
    @GetMapping(value = "/selectAccountBalance")
    public Result getBalanceByAccountId(HttpServletRequest request) throws Exception{
        //获取用户
        User user = JwtTokenUtil.getCurrentUser();
        //定义map存放余额
        Map<String, BigDecimal> map = new HashMap();
        //判断是否登陆
        if (Ognl.isNull(user)){
            //若没登陆，返回余额0.00
            map.put("balance", new BigDecimal("0.00"));
            return Result.fail(Constant.MessageConfig.MSG_USER_NOT_LOGIN,map);
        }
        //查询用户余额
        map = accountService.getAccountBalance(user.getAccountId());
        return Result.success(Constant.MessageConfig.MSG_SUCCESS,map);
    }

    /**
     * 忘记密码,手机号获取密码
     *
     * @param tel
     * @return
     * @throws IOException
     */
    @GetMapping(value = "/findPassword/{tel}")
    public Result getPassword(@PathVariable String tel) throws IOException {
        return authService.getPassword(tel);
    }

    /**
     * 根据条件查询供应商列表
     *
     * @param accountInput
     * @return
     */
    @GetMapping(value = "/findAccount")
    public PageInfo search(@Validated AccountInput accountInput)  {
        //获取当前登陆账户
        User user = JwtTokenUtil.getCurrentUser();
        if(user==null || !user.getIsAdmin().equals(Constant.ADMIN_STATUS)){
            throw new RuntimeException("unauthorized access");
        }
        List<Account> accountList = accountService.searchAccount(accountInput);
        return new PageInfo(accountList);
    }

    /**
     * 根据id查询供应商详细信息
     *
     * @param id
     * @return
     */

    @GetMapping("/search")
    public Account get(@RequestParam(required = false) Long id){
        id = getAccountId(id);
        return accountService.selectById(id);
    }

    /**
     * 根据id查询供应商详细信息
     *
     * @param id
     * @return
     */
    @GetMapping("/search0")
    public Account get0(@RequestParam(required = false) Long id) {
        id = getAccountId(id);
        return accountService.selectById0(id);
    }

    /**
     * 根据当前登录人角色获取accountId
     * @param id
     *
     * @return
     */
    private Long getAccountId(Long id){
        //获取当前登陆账户
        User user = JwtTokenUtil.getCurrentUser();
        if(user==null){
            throw new RuntimeException("unauthorized access");
        }else if(user.getIsAdmin().equals(Constant.ADMIN_STATUS )&&(id == null || id == 0)){
            throw new RuntimeException("unauthorized access");
        }else if(!user.getIsAdmin().equals(Constant.ADMIN_STATUS )){
            id = user.getAccountId();
        }
        return id;
    }

    /**
     * 查询当前登录用户登录手机号码
     * @return 当前登录用户登录手机号码
     */
    @GetMapping("/LoginPhone")
    public Result getLoginPhone(){
        //获取当前登陆账户
        User user = JwtTokenUtil.getCurrentUser();
        if(user!=null) {
            String tel=user.getUsername();
            return Result.success("查询成功",tel);
        }else {
            return Result.fail(Constant.MessageConfig.MSG_USER_NOT_LOGIN);
        }
    }

    /**
     * 发送验证码
     *
     * @return 验证码信息
     * @throws IOException
     */
    @GetMapping(value = "/sendCode")
    public Result sendCode() throws IOException {
        //获取当前登陆账户
        User user = JwtTokenUtil.getCurrentUser();
        if(null == user){
            return Result.fail(Constant.MessageConfig.MSG_USER_NOT_LOGIN);
        }
        String tel=user.getUsername();
        return authService.sendCode(tel);
    }

    /**
     * 检验验证码
     *
     * @param code
     * @return
     */
    @GetMapping(value = "/verifySmsCode/{code}")
    public Result verifySmsCode(@PathVariable String code) {
        //获取当前登陆账户
        User user = JwtTokenUtil.getCurrentUser();
        if(null == user){
            return Result.fail(Constant.MessageConfig.MSG_USER_NOT_LOGIN);
        }
        if(StringAndDateUtil.isNull(code)){
            return Result.fail("验证码无效");
        }
        return authService.verifySmsCode(user, code);
    }

    /**
     * 密码修改
     * @param encodedPassword
     * @return
     */
    @PostMapping(value = "/updatePassword")
    public Result updatePassword(@RequestBody Map encodedPassword) throws IOException {
        //获取当前登陆账户
        User user = JwtTokenUtil.getCurrentUser();
        if(null == user){
            return Result.fail(Constant.MessageConfig.MSG_USER_NOT_LOGIN);
        }
        return authService.updatePassword(user.getId(), encodedPassword.get("encodedPassword").toString());
    }

    /**
     * 获取地区下级列表
     *
     * @param pid 地区id
     * @return 返回下级列表
     */
    @GetMapping("get")
    public List<SysRegion> findByPid(@RequestParam(required = false) Integer pid) {
        return sysRegionService.findByPid(pid);
    }

    /**
     * 统计已入驻供应商数量
     * @return 已入驻供应商数量
     */
    @GetMapping(value = "/AccountNumber")
    public Result getAccountNumber(){
         int num=accountService.selectAccountNumber();
         return Result.success("查询成功",num);
    }
    
    /**
     * 供应商合同上传
     *
     * @param multipartFile 合同
     * @return 返回合同云存储地址
     */
    @PostMapping(value = "/uploadContract")
    public Result uploadContract(@RequestPart("file") MultipartFile multipartFile,String blobName) {
        //获取当前登陆账户
        User user = JwtTokenUtil.getCurrentUser();
        if(user==null || !user.getIsAdmin().equals(Constant.ADMIN_STATUS)){
        	return Result.fail(so.sao.shop.supplier.config.Constant.MessageConfig.ADMIN_AUTHORITY_EERO);
        }
    	return accountService.uploadContract(multipartFile,blobName);
    }
    
    /**
     * 云端合同下载文件转换
     * @param downloadUrl 文件云端地址
     * @param realFileName 文件云端名称
     * @param request
     * @param response
     * @return
     */
    @GetMapping(value = "/downloadContract")
    public Result download(@RequestParam String downloadUrl, @RequestParam String realFileName, HttpServletRequest request, HttpServletResponse response) throws Exception{
        //获取当前登陆账户
        User user = JwtTokenUtil.getCurrentUser();
        if(user==null){
        	return Result.fail(Constant.MessageConfig.MSG_USER_NOT_LOGIN);
        }
        return DownloadAzureFile.downloadFile(downloadUrl, realFileName, request, response);
    }

    /**
     * 根据商户ID修改当前默认运费规则
     * @param freightRules
     * @return
     */
    @PostMapping("/updateFreightRules/{freightRules}")
    public Result updateRulesByFreightRules(@PathVariable("freightRules") Integer freightRules){
        //获取当前登陆账户
        User user = JwtTokenUtil.getCurrentUser();
        //验证用户是否登陆
        if (null == user || Ognl.isEmpty(user.getAccountId())) {
            return Result.fail(Constant.MessageConfig.MSG_USER_NOT_LOGIN);
        }
        return accountService.updateRulesByFreightRules(user.getAccountId(),freightRules) == true ? Result.success(Constant.MessageConfig.MSG_SUCCESS) : Result.fail("运费规则不完整或不存在！");
    }

}
